/*
 * @Author: Robin
 * @Date: 2021-09-06 11:45:42
 * @LastEditors: Robin
 * @LastEditTime: 2021-09-07 09:45:10
 * @Description: 光合RGB UDP服务
 */
package main

import (
	"fmt"
	"log"
	"net"
	"time"
)

func main() {
	// 创建监听
	socket, err := net.ListenUDP("udp", &net.UDPAddr{
		IP:   net.IPv4(0, 0, 0, 0),
		Port: 6000,
	})
	// socket, err := net.ListenMulticastUDP("udp4", nil, &net.UDPAddr{
	// 	IP:   net.IPv4zero,
	// 	Port: 6666,
	// })
	if err != nil {
		log.Fatalln(err)
	}
	defer socket.Close()

	fmt.Println(socket.LocalAddr())

	buf := make([]byte, 4096)
	sendData := make([]byte, 0)
	for {
		time.Sleep(time.Millisecond * 100)
		// 读取数据
		// buf = buf[0:0]
		n, remoteAddr, err := socket.ReadFromUDP(buf)
		if err != nil {
			fmt.Println("读取数据失败!", err)
			continue
		}
		if n > 0 {
			fmt.Println(n, remoteAddr, string(buf))
			// fmt.Printf("%s\n", buf)
			// fmt.Println(string(buf))

			// ask := string(buf)
			// 发送数据
			// fmt.Println("len", len(buf))
			ask := string(buf[:n-1]) // 去除换行符
			fmt.Println("ask", ask)
			switch ask {
			case "look":
				sendData = []byte(`{"name": "工作室的草缸灯常亮测试名称过长", "ip": "172.30.9.100", "version": "1.0.0"}`)
				break
			}
			_, err = socket.WriteToUDP(sendData, remoteAddr)
			if err != nil {
				fmt.Println("发送数据失败:", err)
			}
		}
	}
}
